$(function(){

    //日期插件初始化
    $('.y-date').val(moment().format("YYYY年"));
    $('.y-date').datetimepicker({
        language:  'zh-CN',
        format: 'yyyy年',
        todayBtn:  1,
        autoclose: 1,
        todayHighlight: 1,
        startView: 4,
        minView:4,
    });
    $('.ym-date').val(moment().format("YYYY-MM"));
    $('.ym-date').datetimepicker({
        language:  'zh-CN',
        format: 'yyyy-mm',
        todayBtn:  1,
        autoclose: 1,
        todayHighlight: 1,
        startView: 3,
        minView:3,
    });

	//录入数据弹窗
    $(document).on("click",".adddata-btn",function(){
    	$("[formTo='add_data']").show();
    })
    //绩效模版弹窗
    .on("click",".template-btn",function(){
        $("[formTo='template_data']").show();
    })


    //绩效查询表格相关元素的隐现
    $(".assesstable-nav").on("click","li.year-check",function(){
        $(".quarter-table").hide();
        $(".quarter-sel").hide();
        $(".year-sel").show();
        $(".year-table").show();
    })
    .on("click","li.quarter-check",function(){
        $(".year-table").hide();
        $(".year-sel").hide();
        $(".quarter-sel").show();
        $(".quarter-table").show();
    })


    //模板弹窗类型的切换
    $(document).on("change",".template-style select",function(){
        if (this.value == 1) {
            templateShow("quarter");
        }
        else{
            templateShow("year");
        }
    })


    //季度模板添加指标
    $(document).on("click",".quarter-table-template .add-target",function(){
        var $tbody = $(this).closest(".template-table").find("table tbody");
        addQuarterTr($tbody);
        
    })
    //年度模板添加指标
    .on("click",".year-table-template .add-target",function(){
        var $tbody = $(this).closest(".template-table").find("table tbody");
        addYearTr($tbody);
    })
    //年度模板添加二级标题
    .on("click",".year-table-template .add-subtarget",function(){
        var $tbody = $(this).closest(".template-table").find("table tbody");
        addYearSubTr($tbody);
    })
    //删除指标或二级标题
    .on("click",".template-table td .remove-btn",function(){
        var $table = $(this).closest("table");
        var $thisTr = $(this).closest("tr");
        $(this).closest("tr").remove();
        addAllTrNo($table,$thisTr);
    })


    //编辑模板
    $(document).on("click",".update_template-btn",function(){
        var tid = $(this).closest(".template-box").attr("id");
        var ttype = $(this).closest(".template-box").attr("ttype");
        $(".report-form").attr({
            "class": "report-form update_template-form"
        });
        $(".template-style select").prop("disabled",true); 
        templateShow(ttype);

        //todo 加载表格数据
        
    })
    //保存编辑信息
    .on("click", ".update_template-form .tip-btn", function () {
        if (checkWTip(this)) {
            addTipHtml(
                "success",
                "保存模板成功！",
                "",
                "确定",
                "green",
                function () {
                    closeWindow();
                }
            );
            // addTipHtml(
            //     "wrong",
            //     "保存模板失败！",
            //     "",
            //     "确定",
            //     "gray",
            //     function () {
            //         closeWindow();
            //     }
            // );
        }
    })
    //新建模板
    .on("click",".insert_template-btn",function(){
        $(".report-form").attr({
            "class": "report-form insert_template-form"
        });
        templateShow("quarter");
        var $quarterTable = $(".quarter-sub-table");
        var $yearTable = $(".year-sub-table");
        for (var i = 0; i <= $quarterTable.length; i++) {
            var $quarterTbody = $($quarterTable[i]).find("tbody");
            addQuarterTr($quarterTbody);
        }
        for (var i = 0; i <= $yearTable.length; i++) {
            var $yearTbody = $($yearTable[i]).find("tbody");
            addYearTr($yearTbody);
        }
        checkScore();
    })
    //保存新建模板信息
    .on("click", ".insert_template-form .tip-btn", function () {
        if (checkWTip(this)) {
            addTipHtml(
                "success",
                "新建模板成功！",
                "",
                "确定",
                "green",
                function () {
                    closeWindow();
                }
            );
            // addTipHtml(
            //     "wrong",
            //     "新建模板失败！",
            //     "",
            //     "确定",
            //     "gray",
            //     function () {
            //         closeWindow();
            //     }
            // );
        }
    })
    //删除模板
    .on("click",".template-delete",function(){
        addTipHtml(
            "ask", 
            "是否确认删除该模板？",
            "与该模板相关的绩效信息也将被删除",
            "删除",
            "red",
            function(){
                addTipHtml(
                    "success", 
                    "模版删除成功！",
                    "",
                    "确定",
                    "green",
                    function(){
                        closeWindow();
                    }
                );
            },
            "取消",
            "gray",
            function(){
                closeWindow();
            }
        );
    })
})




//模板弹窗显示
function templateShow(ttype){
    if (ttype =="quarter") {
        $(".template-style select").val("1");
        $(".template-section").hide();
        $(".year-table-template").hide();
        $(".quarter-table-template").show();
    }
    else{
        $(".template-style select").val("2");
        $(".template-section").show();
        $(".quarter-table-template").hide();
        $(".year-table-template").show();
    }
}

//添加季度模板指标
function addQuarterTr($tbody){
    $tbody.find("tr:last-child").before('<tr><td></td><td>'+
                                            '<textarea class="ipt zdgz-ta" rows="1"></textarea>'+
                                        '</td><td>'+
                                            '<input type="text" class="ipt qz-ip NumDecText" />%'+
                                        '</td><td>'+
                                            '<textarea class="ipt rwyq-ta" rows="1"></textarea>'+
                                        '</td><td>'+
                                            '<textarea class="ipt kpbz-ta" rows="1"></textarea>'+
                                        '</td><td>'+
                                            '<select class="sel fzbm-sl">'+
                                                '<option>营销部</option>'+
                                                '<option>生产技术部</option>'+
                                                '<option>安监部</option>'+
                                            '</select>'+
                                        '</td><td>'+
                                            '<textarea class="ipt bz-ta" rows="1"></textarea>'+
                                        '</td><td>'+
                                            '<input type="button" value="移除" class="btn gray-text gray-red-btn remove-btn" />'+
                                        '</td></tr>');
    checkScore();
    addQuarterTrNo($tbody);
}

//添加年度模板指标
function addYearTr($tbody){
    $tbody.append('<tr><td></td><td>'+
                        '<textarea class="ipt mbrw-ta" rows="1"></textarea>'+
                    '</td><td>'+
                        '<input type="text" class="ipt df-ip NumDecText" />'+
                    '</td><td>'+
                        '<textarea class="ipt khbf-ta" rows="1"></textarea>'+
                    '</td><td>'+
                        '<input type="button" value="移除" class="btn gray-text gray-red-btn remove-btn" />'+
                    '</td></tr>');
    checkScore();
    addYearTrNo($tbody);
}

//添加年度模板二级标题
function addYearSubTr($tbody){
    $tbody.append('<tr class="sec-title"><td>'+
                        '（一）'+
                    '</td><td>'+
                        '<textarea class="ipt sec-bt" rows="1"></textarea>'+
                    '</td><td>'+
                        '<input type="text" class="ipt df-ip" readonly />'+
                    '</td><td></td><td>'+
                        '<input type="button" value="移除" class="btn gray-text gray-red-btn remove-btn" />'+
                    '</td></tr>');
    addYearSubTrNo($tbody);
}

//添加季度模板指标序号
function addQuarterTrNo($tbody){
    var $tr = $tbody.find("tr:not(.middle-total)");
    for (var i = 0; i <= $tr.length; i++) {
        $($tr[i]).find("td:first-child").text(i+1);
    }
}

//添加年度模板二级标题序号
function addYearSubTrNo($tbody){
    var $tr = $tbody.find("tr.sec-title");
    for (var i = 0; i <= $tr.length; i++) {
        $($tr[i]).find("td:first-child").text("（"+NoToChinese(i+1)+"）");
    }
}

//添加年度模板指标序号
function addYearTrNo($tbody){
    var trno = "1";
    var $tr = $tbody.find("tr");
    for (var i = 0; i <= $tr.length; i++) {
        if ($($tr[i]).hasClass("sec-title")) {
            trno = 1;
        }
        else{
            $($tr[i]).find("td:first-child").text(trno);
            trno++;
        }
    }
}

//删除指标或二级标题
function addAllTrNo($table,$thisTr){
    var $tbody = $table.find("tbody");
    if ($table.hasClass("quarter-sub-table")) {
        addQuarterTrNo($tbody);
    }
    else {
        if ($thisTr.hasClass("sec-title")) {
            addYearSubTrNo($tbody);
            addYearTrNo($tbody);
        }
        else{
            addYearTrNo($tbody);
        }
    }
    countScore($tbody);
}


//监听分值输入框
function checkScore (){
    $("input[type='text'].NumDecText").bind('input propertychange', function() {
        var $this = $(this),
            $tbody = $this.closest("tbody");
        countScore($tbody);
    });

    //控制数字输入框只能输入数字跟小数点
    $(".NumDecText").keyup(function(){
        $(this).val($(this).val().replace(/[^0-9.]/g,''));
    }).bind("paste",function(){  //CTR+V事件处理
        $(this).val($(this).val().replace(/[^0-9.]/g,''));
    })
}

//计算分值总和
function countScore($tbody){
    var $subtotal = $tbody.find(".subtotal"),
        $score = $tbody.find(".NumDecText");
    var $quarterTotal = $(".quarter-table-template .alltotal"),
        $quarterScore = $(".quarter-table-template").find(".NumDecText");
    var $yearTotal = $(".year-table-template .alltotal"),
        $yearScore = $(".year-table-template").find(".NumDecText");
    var scores="0",
        quarterScores = "0",
        yearScores = "0";

    for (var i = 0; i < $score.length; i++) {
        var ss = $($score[i]).val()?$($score[i]).val():"0";
        scores = parseInt(scores) + parseInt(ss);
    }
    $subtotal.val(scores);

    for (var i = 0; i < $quarterScore.length; i++) {
        var ss = $($quarterScore[i]).val()?$($quarterScore[i]).val():"0";
        quarterScores = parseInt(quarterScores) + parseInt(ss);
    }
    $quarterTotal.val(quarterScores);

    for (var i = 0; i < $yearScore.length; i++) {
        var ss = $($yearScore[i]).val()?$($yearScore[i]).val():"0";
        yearScores = parseInt(yearScores) + parseInt(ss);
    }
    $yearTotal.val(yearScores);      
}

